package info.batcloud.fanli.admin.controller;

import com.ctospace.archit.common.pagination.Paging;
import info.batcloud.fanli.core.dto.UserWithdrawDTO;
import info.batcloud.fanli.core.exception.BizException;
import info.batcloud.fanli.core.helper.StringHelper;
import info.batcloud.fanli.core.service.UserWithdrawService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user-withdraw")
public class UserWithdrawController {

    @Inject
    private UserWithdrawService userWithdrawService;

    @GetMapping("/search")
    public Object search(UserWithdrawService.SearchParam param) {
        Paging<UserWithdrawDTO> paging = userWithdrawService.search(param);
        paging.setResults(paging.getResults().stream().map(w -> {
            w.setPayeeName(StringHelper.protect(w.getPayeeName()));
            w.setPayeeAccount(StringHelper.protect(w.getPayeeAccount()));
            w.setUserPhone(StringHelper.protect(w.getUserPhone()));
            return w;
        }).collect(Collectors.toList()));
        return paging;
    }

    @PutMapping("/verify")
    public Object verify(UserWithdrawService.VerifyParam param) {
        userWithdrawService.verify(param);
        return 1;
    }

    @PostMapping("/fund-transfer/{id}")
    public Object fundTransfer(@PathVariable long id) {
        return userWithdrawService.withdrawFundTransferById(id);
    }

    @PostMapping("/manual-fund-transfer")
    public Object manualFundTransfer(UserWithdrawService.ManualFundTransferParam param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BizException("参数错误");
        }
        return userWithdrawService.withdrawManualFundTransfer(param);
    }

    @GetMapping("/export")
    public Object export(UserWithdrawService.ExportParam param, HttpServletResponse response) throws IOException {
        File file = userWithdrawService.exportXsl(param);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("提现", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + System.currentTimeMillis() + ".xls");
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            file.delete();
        }
        return null;
    }
}
